package com.zh.template;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.zh.constants.ErrorCode;
import com.zh.pojo.bo.OpenIdResponseBo;
import com.zh.properties.WxMinAppProperties;
import com.zh.utils.AssertUtil;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;

/**
 * 微信相关的工具类  获取微信OpenId , 获取AccessToken  获取手机号
 */
public class WeChatTemplate {

    private RestTemplate restTemplate;
    private WxMinAppProperties minAppProp;

    public WeChatTemplate(WxMinAppProperties minAppProp, RestTemplate restTemplate) {
        this.minAppProp = minAppProp;
        this.restTemplate = restTemplate;
    }


    /**
     * 获取 微信 OpenId
     * @param wechatCode 微信的授权码
     * @return
     */
    public String getOpenId(String wechatCode) {
        //3、通过获取的三个参数拼接url
        // https://api.weixin.qq.com/sns/jscode2session?appid=APPID&secret=SECRET&js_code=JSCODE&grant_type=authorization_code,
        // 拼接好Url地址后通过RestTemplate 发送get请求
        ResponseEntity<String> responseEntity =
                restTemplate.getForEntity(String.format(minAppProp.getUrlOpenid(), minAppProp.getAppId(),
                                minAppProp.getAppSecret(),
                                wechatCode),
                        String.class);
        //4、拿到openId （用户唯一标识）
        String entityBody = responseEntity.getBody();
        // 将String类型 中数据转为JSON 对象
        OpenIdResponseBo parseObject = JSON.parseObject(entityBody, OpenIdResponseBo.class);
        AssertUtil.isNotNull(parseObject, "String类型转JSON对象失败");
        // TODO: 判断错误码信息，
        AssertUtil.isFalse(ObjectUtil.equal(parseObject.getErrcode(), ErrorCode.PARAM_ERR_CODE.getCode()),
                ErrorCode.PARAM_ERR_CODE.getMessage());
        //5、判断openId是否存在 如果存在说明已注册
        //获取openId
        return parseObject.getOpenid();
    }


}
